from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth.models import AnonymousUser
from .models import Project
import logging

logger = logging.getLogger(__name__)

class ProjectAPIKeyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        logger.debug(f"认证头: {auth_header}")
        
        if not auth_header:
            logger.debug("没有认证头")
            return None
        
        if not auth_header.startswith('Bearer '):
            logger.debug("不是Bearer格式")
            return None
        
        api_key = auth_header[7:]
        logger.debug(f"提取的API Key: {api_key}")
        
        if not api_key.startswith('lwh_'):
            logger.error("API Key格式错误")
            raise AuthenticationFailed('Invalid API key format')
        
        try:
            project = Project.objects.get(api_key=api_key)
            logger.debug(f"找到项目: {project.name}")
            request.project = project
            return (AnonymousUser(), None)
        except Project.DoesNotExist:
            logger.error(f"API Key不存在: {api_key}")
            raise AuthenticationFailed('Invalid API key')
    
    def authenticate_header(self, request):
        return 'Bearer'